package com.bskyb.rss.widget;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.SystemClock;
import android.util.Log;

import com.bskyb.rss.R;
import com.bskyb.rss.configure.RssFeedWidgetConfiguration;
import com.bskyb.rss.service.RssReaderService;

public class SkyNewsReaderAppWidget extends AppWidgetProvider {
	public static final String URI_SCHEME = "newsreader_widget";
	static final String TAG = "SkyNewsReaderAppWidget";
	
	 @Override
	 public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		 	Log.e(TAG, "Entering OnUpdate with widget id.."+appWidgetIds[0]);		 
			for (int mAppWidgetId : appWidgetIds) {
				Intent newIntent = new Intent(context,
						RssReaderService.class);
				newIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
						mAppWidgetId);					
				context.startService(newIntent);
			}
			Log.e(TAG, "Exiting OnUpdate with widget id..");
	 }


	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {		
		Log.e(TAG, "Entering onDeleted");
		
		for (int appWidgetId : appWidgetIds) {
			// stop alarm
			Intent widgetUpdate = new Intent(context,
					SkyNewsReaderAppWidget.class);
			widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
			widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
					new int[] { appWidgetId });
			widgetUpdate.setData(Uri.withAppendedPath(Uri.parse(URI_SCHEME
					+ "://widget/id/"), String.valueOf(appWidgetId)));
			PendingIntent newPending = PendingIntent.getBroadcast(context, 0,
					widgetUpdate, PendingIntent.FLAG_UPDATE_CURRENT);
			
			AlarmManager alarms = (AlarmManager) context
					.getSystemService(Context.ALARM_SERVICE);
			alarms.cancel(newPending);

			// remove preference
			Log.d("SkyNewsReaderAppWidget", "Removing preference for id "+ appWidgetId);
			removePreference(context, appWidgetId,
					R.id.widget_configuration_dropdown);
			removePreference(context, appWidgetId,
					R.id.widget_configuration_siteselection_dropdown);
			removePreference(context, appWidgetId,
					R.id.widget_configuration_feedrefresheditbutton);
		}

		super.onDeleted(context, appWidgetIds);
		Log.e(TAG, "Exiting onDeleted");
	}

	private void removePreference(Context context, int appWidgetId,
			int layoutWidgetId) {
		Log.e(TAG, "Entering removePreference");
		SharedPreferences config = context.getSharedPreferences(
				RssFeedWidgetConfiguration.PREFS_NAME, 0);
		SharedPreferences.Editor configEditor = config.edit();
		configEditor.remove(RssFeedWidgetConfiguration.PREFS_NAME + appWidgetId
				+ layoutWidgetId);
		configEditor.commit();
		Log.e(TAG, "Exiting removePreference");
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.e(TAG, "Entering onReceive");
		final String action = intent.getAction();
		Log.e("SkyNewsReaderAppWidget", "OnReceive:Action: " + action);
		Log.e("SkyNewsReaderAppWidget", "intent.getScheme(): " + intent.getScheme());
		Log.e("SkyNewsReaderAppWidget", "intent.getStringExtra(unique): " + intent.getStringExtra("unique"));
		if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {			
			final int appWidgetId = intent.getExtras().getInt(
					AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
			if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
				this.onDeleted(context, new int[] { appWidgetId });
			}
		} else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {

			if (!URI_SCHEME.equals(intent.getScheme()) && intent.getExtras()!=null) {

				final int[] appWidgetIds = intent.getExtras().getIntArray(
						AppWidgetManager.EXTRA_APPWIDGET_IDS);
				for (int mAppWidgetId : appWidgetIds) {
					//Retrieve shared preference object and do stuff for alarm configuration
					Intent widgetUpdate = new Intent(context,
							SkyNewsReaderAppWidget.class);
					widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
							new int[] { mAppWidgetId });
					widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
					widgetUpdate.putExtra("unique", "unique");

					// make this pending intent unique
					widgetUpdate.setData(Uri.withAppendedPath(
							Uri.parse(SkyNewsReaderAppWidget.URI_SCHEME
									+ "://widget/id/"), String.valueOf(mAppWidgetId)));
					PendingIntent newPending = PendingIntent.getBroadcast(
							context, 0, widgetUpdate,
							PendingIntent.FLAG_UPDATE_CURRENT);

					// schedule the new widget for updating
					AlarmManager alarms = (AlarmManager) context
							.getSystemService(Context.ALARM_SERVICE);
					int updateRateInMins = Integer.parseInt(getSharedPreferenceForFeedRefreshTime(context,mAppWidgetId));
					alarms.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock
							.elapsedRealtime(), updateRateInMins * 1000 * 60,
							newPending);
					

				}

			}
			else if(URI_SCHEME.equals(intent.getScheme()) && "unique".equalsIgnoreCase(intent.getStringExtra("unique"))){
				Log.e(TAG, "IGNORING BLANKET UPDATE!!!");
			}
			super.onReceive(context, intent);
		} else{
			super.onReceive(context, intent);
		}
		
		Log.e(TAG, "Exiting onReceive");

	}


	private String getSharedPreferenceForFeedRefreshTime(Context context, int appWidgetId) {
		SharedPreferences prefs = context.getSharedPreferences(
				RssFeedWidgetConfiguration.PREFS_NAME, Context.MODE_WORLD_READABLE);
		String feedRefreshTime = prefs.getString(
				RssFeedWidgetConfiguration.PREF_PREFIX_KEY + appWidgetId
						+ R.id.widget_configuration_feedrefresheditbutton, "10");
		Log.e(TAG, "VAlue obtained is.."+feedRefreshTime);
		
		// TODO Auto-generated method stub
		return feedRefreshTime;
	}

}
